/* eslint-disable array-callback-return */
/* eslint-disable no-unused-expressions */
/* eslint-disable react/destructuring-assignment */
// 地区模糊查询
import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Row, Col, InputNumber, Input, Upload, Button, message } from 'antd';
import { requestHeadersMd5 } from '@/utils/utils';

const FormItem = Form.Item;
const { TextArea } = Input;
@Form.create()
class UpdateModal extends React.Component {
  state = {
    oldAffix: [],
    isState: true,
  };

  clearIsState = () => {
    this.setState({
      isState: true,
      oldAffix: [],
    });
  };

  handleOk = () => {
    const {
      form: { validateFieldsAndScroll },
      data,
    } = this.props;
    const { oldAffix } = this.state;
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        const newValues = values;
        let affixValue = '';
        if (oldAffix.length) {
          oldAffix.forEach(item => {
            const idArr = !!item.url ? item.url.split('=') : item.fileUrl.split('=')
            const idArr1 = idArr[1].split('&')
            const idArr2 = idArr1[0]
            affixValue += `${idArr2
              .concat('|')
              .concat(item.name)
              .concat(',')}`;
            delete newValues.oldAffix;
            newValues.affix = affixValue ? affixValue.slice(0, affixValue.length - 1) : null;
          });
        } else {
          newValues.affix = '';
          delete newValues.oldAffix;
        }
        newValues.reimbAmt = values.reimbAmt ? values.reimbAmt : data.reimbAmt;
        this.props.onOk(newValues);
      }
    });
  };

  handleCancle = () => {
    this.props.onCancel && this.props.onCancel();
  };

  changeUpload = ({ file, fileList }, listContFile, getFieldName) => {
    const { downloadUrl } = this.state;
    const { form } = this.props;
    const newData = listContFile.map(item => ({ ...item }));

    if (file.status === 'done' && file.response.success) {
      const uid = file.response.data.split('|')[0];
      const name = file.response.data.split('|')[1];
      fileList.map(files => {
        const fileObj = files;
        fileObj.url = `${downloadUrl}?fileId=${uid}&fileName=${name}`;
        fileObj.linkProps = { download: `${name}` };
      });
      newData.push({
        uid: file.uid,
        fileFileid: uid,
        name,
        fileUrl: `${downloadUrl}?fileId=${uid}&fileName=${name}`,
      });
      form.setFieldsValue({ [getFieldName]: newData });
      this.setState({ [getFieldName]: newData, isState: false });
      message.success('文件上传成功！');
    }
    if ((file.status === 'done' && !file.response.success) || file.status === 'error') {
      fileList.map(files => {
        const fileObj = files;
        if (files.uid === file.uid) {
          fileObj.status = 'error';
          fileObj.response = '服务端错误';
        }
      });
      const newDatas = fileList.filter(item => item.uid !== file.uid);
      form.setFieldsValue({ [getFieldName]: newDatas });
      this.setState({ [getFieldName]: newDatas, isState: false });
      message.error('上传失败！');
    }
  };

  // 移除文件
  removeFile = (file, listContFile, getFieldName) => {
    const newData = listContFile.filter(item => item.uid !== file.uid);
    this.setState({ [getFieldName]: newData, isState: false });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { data } = this.props;
    let { oldAffix } = this.state;
    const { downloadUrl } = this.state;
    const { isState } = this.state;
    if (data && data.affix) {
      const newObj = data.affix.split(',');
      if (newObj.length && isState) {
        oldAffix = newObj.map(item => ({
          uid: item.split('|')[0],
          name: item.split('|')[1],
          status: 'done',
          url: `${downloadUrl}?fileId=${item.split('|')[0]}&fileName=${item.split('|')[1]}`,
          linkProps: { download: `${item.split('|')[1]}` },
        }));
      }
    }

    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 16 } },
    };
    const uploadProps = {
      name: 'file',
      action: '/osApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      onChange: info => this.changeUpload(info, oldAffix, 'oldAffix'),
      onRemove: file => this.removeFile(file, oldAffix, 'oldAffix'),
    };

    // 上传部分
    const uploadFileFormat = e => {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    };

    return (
      <Modal
        title={this.props.title}
        visible={this.props.visible}
        onOk={this.handleOk}
        onCancel={this.handleCancle}
        destroyOnClose
        afterClose={this.clearIsState}
      >
        <div>
          <Row>
            <Col>
              {data.reimbAmt ? (
                <FormItem {...formItemLayout} label="报销金额（元）">
                  {data.reimbAmt && data.reimbAmt.toFixed(2)}
                </FormItem>
              ) : (
                <FormItem {...formItemLayout} label="报销金额（元）">
                  {getFieldDecorator('reimbAmt', {
                    rules: [
                      {
                        required: true,
                        message: '请输入小数点不超过2位的数字报销金额（元）',
                        pattern: /^[0-9]{0,7}(\.[0-9]{1,2})?$/,
                      },
                    ],
                    initialValue: data.reimbAmt && data.reimbAmt.toFixed(2),
                  })(
                    <InputNumber
                      placeholder="请输入"
                      step={0.01}
                      style={{ width: '100%' }}
                      disabled
                    />
                  )}
                </FormItem>
              )}
            </Col>
          </Row>
          <Row>
            <Col>
              <FormItem {...formItemLayout} label="本次返款金额（元）">
                {getFieldDecorator('refundAmt', {
                  rules: [
                    {
                      required: true,
                      message: '请输入小数点不超过2位的数字本次返款金额（元）',
                      pattern: /^[0-9]{0,7}(\.[0-9]{1,2})?$/,
                    },
                  ],
                  initialValue: data.refundAmt && data.refundAmt.toFixed(2),
                })(<InputNumber placeholder="请输入" step={0.01} style={{ width: '100%' }} />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col>
              <FormItem {...formItemLayout} label="上传凭证">
                {getFieldDecorator('oldAffix', {
                  valuePropName: 'fileList',
                  getValueFromEvent: uploadFileFormat,
                  initialValue: oldAffix,
                })(
                  <Upload {...uploadProps}>
                    <Button>
                      <UploadOutlined /> 上传附件
                    </Button>
                  </Upload>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col>
              <FormItem {...formItemLayout} label="返款备注">
                {getFieldDecorator('remark', {
                  initialValue: data.remark,
                })(
                  <TextArea
                    placeholder="请输入"
                    autosize={{ minRows: 3, maxRows: 6 }}
                    maxLength="100"
                  />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row style={{ marginBottom: 20 }}>
            <Col>
              <span style={{ color: 'red' }}>
                注：若报销金额不对，待认领状态下可先作废已添加的返款信息，重新新增返款信息
              </span>
            </Col>
          </Row>
        </div>
      </Modal>
    );
  }
}
export default UpdateModal;
